package org.person.demo.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.person.demo.service.FlowLimitService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;

@RestController
@Slf4j
public class FlowLimitController {

    @Resource
    private FlowLimitService service;

    @GetMapping("/testA")
    public String testA() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return service.test("testA========");
    }

    @GetMapping("/testB")
    public String testB() {
        log.info(Thread.currentThread().getName() + "\ttestB");
        return service.test("testB========");
    }

    @GetMapping("/testD")
    public String testD() {
        int sleepTime = new Random().nextInt(5) + 1;
        log.info(Thread.currentThread().getName() + "\ttestD,sleep:" + sleepTime * 100 + "ms");
        try {
            Thread.sleep(sleepTime * 100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "testD======" + sleepTime * 100;
    }

    @GetMapping("/testBreakException")
    public String testBreakException() {
        int random = new Random().nextInt(100);
        if (random % 2 == 0)
            throw new RuntimeException("testBreakException======熔断异常测试");
        return "testBreakException======" + random;
    }

    @GetMapping("/hot/keys")
    @SentinelResource("testHotKeys")
    public String testHotKeys(@RequestParam(value = "a", required = false)String a,
                              @RequestParam(value = "b", required = false) String b) {
        return "testHotKeys======," + "a:" + a + ", b:" + b;
    }
}
